<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 0px;
            top: 0px;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background: blue;
            position: absolute;
            left: 50px;
            top: 200px;
        }
    </style>
</head>

<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
        var box1Ele = document.querySelector(".box1");
        let speed = 5;
        let dir = "left";
        setInterval(function () {
           
            document.onkeydown = function(e){
                var key = e.key;
                // console.log(key);
                if(key=='ArrowDown'){
                    console.log("下");
                    dir = "top";
                }
                if(key=="ArrowRight"){
                    dir = "left";
                }
            }

           
           console.log(dir);
            // 先获取元素原本的left值 然后再加一个速度值；
            // 获取非行间样式；
            var leftNum = parseInt(getComputedStyle(box1Ele, null)[dir]);
            // console.log(leftNum);
            var dis = window.innerWidth - box1Ele.offsetWidth;
            // console.log(dis);
           
            if(leftNum>=dis){
                speed *=-1;
            }

            if(leftNum<0){
                speed *=-1;
            }
           
            var res = leftNum + speed;
           
            box1Ele.style[dir] = res + "px";
        }, 20);



    </script>
</body>

</html>